﻿using System;
using System.Net.Http.Headers;
using System.Text;
using Hangfire.Dashboard;
using Microsoft.AspNetCore.Http;

namespace Colorful.Furniture.BackgroundWorkerManagement;

/// <summary>
///  hangfire认证筛选器
/// </summary>
public class HangfireAuthorizationFilter : IDashboardAuthorizationFilter
{
    /// <summary>
    ///  认证
    /// </summary>
    /// <param name="context"></param>
    /// <returns></returns>
    public bool Authorize(DashboardContext context)
    {
        var httpContext = context.GetHttpContext();
        string header = httpContext.Request.Headers["Authorization"];//获取授权
        if (header == null)
            return AuthorizationLogin();
        //解析授权
        var authHeader = AuthenticationHeaderValue.Parse(header);

        if (authHeader.Parameter == null)
            return false;

        var credentialBytes = Convert.FromBase64String(authHeader.Parameter);
        var credentials = Encoding.UTF8.GetString(credentialBytes).Split(new[] { ':' }, 2);
        var username = credentials[0];
        var password = credentials[1];

        //验证登录
        if (username == "hangfire" && password == "123@qwe")
            return true;

        return AuthorizationLogin();

        //跳转简单认证登录界面
        bool AuthorizationLogin()
        {
            httpContext.Response.StatusCode = 401;
            httpContext.Response.Headers.Append("WWW-Authenticate", "Basic realm=\"Hangfire Dashboard\"");
            context.Response.WriteAsync("请先登录操作");
            return false;
        }

    }
}